const catchAsync = require('../utils/catchAsync');
const AppError = require("../utils/appError");
const APIFeatures = require('../utils/apiFeatures');
exports.deleteOne = Model => catchAsync(async (req, res,next) => {
    const doc = await Model.findByIdAndDelete(req.params.id);

    if(!doc){
        return next(new AppError('No document found with that ID',404))
    }


    res.status(204).json({
        status: 'success',
        data: '删除成功'
    })
})

exports.updateOne = Model => catchAsync(async (req, res,next) => {
    const doc = await Model.findByIdAndUpdate(req.params.id, req.body, {
        new: true,
        runValidators: true,
    })
    if(!doc){
      return  next(new AppError(`No document with Id`,404));
    }
    res.status(200).json({
        status: 'success',
        data: {
            data: doc
        }
    })
})

exports.createOne = Model => catchAsync(async (req, res,next) => {
    const doc = await Model.create(req.body);

    res.status(201).json({
        status: "success",
        data: {
            data: doc
        }
    })
    // res.send('Done'); 发送请求后无法设置请求头
})

exports.getOne = (Model,popOptions) => catchAsync(async (req, res,next) => {
    // populate 虚拟聚合
    let query = Model.findById(req.params.id);
    if(popOptions) query = query.populate(popOptions)
    const doc = await query
    // // Tour.findOne({_id:req.params.id})
    if(!doc){
        return next(new AppError(`Cant find id on this server`,404));
    }
    res.status(200).json({
        status: 'success',
        data: {
            doc
        }
    })
})

exports.getAll = Model => catchAsync(async (req, res,next) => {
    const features = new APIFeatures(Model.find(), req.query)
        .filter()
        .sort()
        .limitFiedlds()
        .paginate();
    const doc = await features.query;
    //
    // const doc = await features.query.explain();
    // 发送回复
    res.status(200).json({
        status: 'success',
        results: doc.length,
        data: {
            data:doc
        }
    })
})

    // 建立query
    // 1A. 过滤
    // const queryObj = {
    //     ...req.query
    // };
    // const excludeFields = ['page', 'sort', 'limit', 'fields'];
    // excludeFields.forEach(el => delete queryObj[el]); // 这个delete方法
    // // 1B.高级过滤
    // let queryStr = JSON.stringify(queryObj);
    // queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, match => `$${match}`);
    // console.log(JSON.parse(queryStr), 'first filter');

    // 2. 分类
    // let query = Tour.find(JSON.parse(queryStr)); // 查询数据
    // if(req.query.sort){
    //     const sortBy = req.query.sort.split(',').join(' ');
    //     console.log(sortBy,'first sort');
    //     query = query.sort(sortBy);
    // }else{
    //     query = query.sort('-createdAt');
    // }

    // 3.field limiting 限制返回字段
    // if (req.query.fields) {
    //     const fields = req.query.fields.split(',').join(' ');
    //     console.log(fields)
    //     console.log(fields, 'first fields');
    //     query = query.select(fields) // 方法未知
    // } else {
    //     query = query.select('-__v'); // 负号代表排除的意思
    // }

    // 4) 分页
    // const page = req.query.page * 1 || 1;
    // const limit = req.query.limit * 1 || 100;
    // const skip = (page - 1) * limit;
    // query = query.skip(skip).limit(limit);
    // if (req.query.page) {
    //     const numTours = await Tour.countDocuments();
    //     if (skip >= numTours) throw new Error('This page does not exist');
    // }

    // 执行query